﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCServer.Entities.Commands;
using IRCServer.Entities;
using IRCServer.Utilities;
using IRCServer.Backend;

namespace IRCServer.CommandHandlers
{
    class NICKCommandHandler : CommandHandlerBase
    {
        public override string HandleCommand(IRCCommandBase command, Session session)
        {
            if (command is NICKCommand)
            {
                NICKCommand nickCommand = (NICKCommand)command;

                if (nickCommand.Nickname == null)
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NONICKNAMEGIVEN, string.Empty);
                }

                List<User> filteredUsers = ServerBackend.Instance.Users.Where(u => u.Nickname != null && u.Nickname.ToLower() == nickCommand.Nickname.ToLower()).ToList();

                if (filteredUsers.Count() > 0 && (session.User == null || (session.User != null && filteredUsers[0] != session.User)))
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NICKNAMEINUSE, nickCommand.Nickname);
                }

                if (session.User != null)
                {
                    session.User.Nickname = nickCommand.Nickname;
                }
                else
                {
                    session.User = new User()
                    {
                        Nickname = nickCommand.Nickname
                    };

                    ServerBackend.Instance.Users.Add(session.User);
                }

                UpdateConnectionState(session);

                return "OK";
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}
